import * as _ from "lodash"
import { useEffect, useState } from "react"

type LoadingState = boolean | boolean[]

function reduceState(states ?: LoadingState): boolean {
  if (_.isBoolean(states)) {
    return states
  }
  if (_.isArray(states)) {
    return _.reduce(states, (state: boolean, current) => state || current, false)
  }
  return false
}

export function useLoading(states: LoadingState): [boolean, (state: LoadingState) => void] {
  const [loading, setLoading] = useState<boolean>(false)
  const aState = reduceState(states)
  useEffect(() => setLoading(aState), [aState])
  return [loading, (dState: LoadingState) => setLoading(reduceState(dState))]
}
